package grpc

import (
	"fmt"
	"gitee.com/zhouxiaozhu/go-delayqueue/client/cmd/grpc/controller"
	"gitee.com/zhouxiaozhu/go-delayqueue/client/cmd/grpc/pb/delay"
	"gitee.com/zhouxiaozhu/go-delayqueue/client/initializers"
	"github.com/sirupsen/logrus"
	"log"
	"net"

	"github.com/spf13/cobra"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	healthPb "google.golang.org/grpc/health/grpc_health_v1"
	"google.golang.org/grpc/reflection"
)

const HealthcheckService = "grpc.health.v1.Health"

// Cmd ...
var Cmd = &cobra.Command{
	Use:   "grpc",
	Short: "grpc server",
	Long:  `run your grpc server`,
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("grpc called")
		initializers.Init()

		startServer()
	},
}

func startServer() {
	lis, err := net.Listen("tcp", fmt.Sprintf(":%d", 5000))
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}

	var opts []grpc.ServerOption
	grpcServer := grpc.NewServer(opts...)

	// 健康检查
	healthServer := health.NewServer()
	healthServer.SetServingStatus(HealthcheckService, healthPb.HealthCheckResponse_SERVING)
	healthPb.RegisterHealthServer(grpcServer, healthServer)

	// 注册 grpcurl 所需的 reflection 服务
	reflection.Register(grpcServer)

	// 注册业务服务
	delay.RegisterDelayServer(grpcServer, &controller.DelayServer{})

	if err := grpcServer.Serve(lis); err != nil {
		logrus.Fatal(fmt.Sprintf("failed to serve: %v", err))
	}
}
